package com.wwwarehouse.common.tools;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @创建者 chenchao.
 * @创建时间 2016/11/16 16:32
 * @描述 ${TODO}
 */
public class RecordArmUtils {

    MediaRecorder mMediaRecorder;
    Context       mContext;
    private MediaPlayer mMediaPlayer;
    private File        mFile;

    public RecordArmUtils(Context context, MediaRecorder mMediaRecorder){
        mContext = context;
        this.mMediaRecorder = mMediaRecorder;
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {//异常处理的地方。
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mMediaPlayer.reset();
                return false;
            }
        });
    }

    public void recordVolume(ArrayList arrayList) {
        try {
            if(mMediaRecorder==null){
                mMediaRecorder = new MediaRecorder();
            }
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                return;
            }
            /* 创建录音频临时文件，  dongjie开头，.amr结尾， 最后一个参数是文件录音完之后存放的路径 */
            File myRecAudioFile = File.createTempFile("chenchao", ".mp3", new FileUtils().getRecordPath());
            /* 设置录音来源为麦克风 */
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mMediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath());
            mMediaRecorder.prepare();
            mMediaRecorder.start();
            arrayList.add(myRecAudioFile.getAbsolutePath());
            LogUtils.showErrLog("recording: " + myRecAudioFile.getAbsolutePath());
//            Toast.makeText(mContext, myRecAudioFile.getName(), Toast.LENGTH_SHORT).show();
//            adapter.notifyDataSetChanged();
        }
        catch (Exception e) {
            LogUtils.showErrLog("recording: " + e.toString());
        }
    }

    /**
     * 停止录音
     */
    public void stopRecordVolume() {
        /* 停止录音 */
        if (mMediaRecorder == null) {
            return ;
        }
        try{
            mMediaRecorder.stop();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }catch (IllegalStateException e){
//            List <String> pers = new LinkedList<>();
//            pers.add(Manifest.permission.RECORD_AUDIO);
//            PermissionUtils.permissionDialog((Activity)mContext,pers,null);
            Toast.makeText(mContext,"没有赋予权限",Toast.LENGTH_LONG).show();
        }

    }

    /**
     * MediaPlayer播放录音(文件)
     * @param file
     */
    public void playRecordVolume(String file) throws IOException {

        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(file);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        /*默认播放器下载   使用默认播放器播放录音*/
//        Intent intent = new Intent();
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction(Intent.ACTION_VIEW);
//        String type = getMIMEType(file);
//        intent.setDataAndType(Uri.fromFile(file), type);
//        mContext.startActivity(intent);
    }


    /**
     * MediaPlayer播放录音(文件)
     * @param file
     */
    public void playRecordVolume(String file ,MediaPlayer.OnCompletionListener listener) throws IOException {

//        if(mMediaPlayer.){
//
//        }
        mMediaPlayer.setOnCompletionListener(listener);
        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(file);
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        /*默认播放器下载   使用默认播放器播放录音*/
//        Intent intent = new Intent();
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.setAction(Intent.ACTION_VIEW);
//        String type = getMIMEType(file);
//        intent.setDataAndType(Uri.fromFile(file), type);
//        mContext.startActivity(intent);
    }

    /**
     * 使MediaPlayer播放录音(网络文件)
     */
    public void playRecordVolumeUrl(String url, MediaPlayer.OnCompletionListener listener) {
        try {
//            stop();
            mMediaPlayer.setOnCompletionListener(listener);
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(url);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (Exception e) {
            stop();
            e.printStackTrace();
        }
    }

    /**
     * 获取文件类型
     * @param f
     * @return
     */
    public String getMIMEType(File f) {
        String end = f.getName().substring(f.getName().lastIndexOf(".") + 1, f.getName().length())
                .toLowerCase();
        String type = "";
        if (end.equals("mp3") || end.equals("aac") || end.equals("aac")
                || end.equals("amr") || end.equals("mpeg")
                || end.equals("mp4")) {
            type = "audio";
        }
        else if (end.equals("jpg") || end.equals("gif")
                || end.equals("png") || end.equals("jpeg")) {
            type = "image";
        }
        else {
            type = "*";
        }
        type += "/*";
        return type;
    }

    /**
     * 删除录音
     */
    public void deleteRecordVolume() {
//        recordFiles.remove(pos);
//        adapter.notifyDataSetChanged();
//
//        if (myPlayFile.exists()) {
//            myPlayFile.delete();
//        }
    }


    /**
     * 删除文件夹里的文件
     * @return
     */
    public  void delete(File file) {
                if (file.isFile()) {
                    file.delete();
                    return;
                }

        if(file.isDirectory()){
                File[] childFiles = file.listFiles();
                    if (childFiles == null || childFiles.length == 0) {
//                        file.delete();
                            return;
                        }

                   for (int i = 0; i < childFiles.length; i++) {
                           delete(childFiles[i]);
                       }
//            file.delete();（删除该文件夹）
               }
          }

    public int getPlayDuration(String path){
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {

            mediaPlayer.reset();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.showErrLog("" + e.getStackTrace());
        }
        return mediaPlayer.getDuration();
    }
    /**
     * mMediaPlayer是否在播放
     * @return
     */
    public boolean isPlaying(){
        if(mMediaPlayer != null){
            return mMediaPlayer.isPlaying();
        }else{
            return false;
        }
    }
    /**
     * mMediaPlayer去停止
     * @return
     */
    public void stop(){
        if(mMediaPlayer != null && mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
        }
    }
}
